import { defineStore } from 'pinia';
import { ref, computed, watch, onMounted, toRaw } from 'vue';
import _ from 'lodash';
import localforage from 'localforage';

export default defineStore('Rcs2Agv', () => {

  const rcs2AgvList = ref<RcsAgvInfoVo[]>([]);
  const customAgvList = ref<CustomAgvInfo[]>([]);
  const selectedAgvId = ref<string | null>(null);
  const selectedAgvIp = ref<string | null>(null);
  const isAgvListLoading = ref(false);
  window['agvList'] = rcs2AgvList;

  // 初始化时加载自定义车列表
  async function initializeCustomAgvList() {
    const stored = await localforage.getItem('customAgvList');
    if (stored) {
      customAgvList.value = stored as CustomAgvInfo[];
    }
  }

  // 保存自定义车列表到本地存储
  async function saveCustomAgvList() {
    await localforage.setItem('customAgvList', toRaw(customAgvList.value));
  }

  // 添加自定义车
  async function addCustomAgv({ agvId, ip }: { agvId: string, ip: string }) {
    // 检查是否已存在相同车号的自定义车
    const existingIndex = customAgvList.value.findIndex(agv => agv.agvId === agvId);

    if (existingIndex >= 0) {
      // 更新现有自定义车的IP
      customAgvList.value[existingIndex].ip = ip;
    } else {
      // 添加新的自定义车
      customAgvList.value.push({
        agvId,
        ip,
        type: 'CUSTOM',
        isOnline: false,
        displayStatus: 1,
        mode: '',
        soc: 0,
        logicX: 0,
        logicY: 0,
        direction: '',
        agvModelType: 'CUSTOM',
        httpPort: 8080,
        wsPort: 9000
      });
    }

    // 保存到本地存储
    await saveCustomAgvList();
  }

  // 删除自定义车
  async function removeCustomAgv(agvId: string) {
    const index = customAgvList.value.findIndex(agv => agv.agvId === agvId);
    if (index >= 0) {
      customAgvList.value.splice(index, 1);
      await saveCustomAgvList();
    }
  }

  function clearList() {
    rcs2AgvList.value = [];
  }

  function updateAgvList(data: RcsAgvInfoVo[]) {
    // 对 data Vid 进行排序, 并添加  httpPort: 8080, / wsPort: 9000, 字段
    data.sort((a, b) => {

      // 判断是否离线（优先级最高，即使同时异常也归为离线）
      const isOffline = (item) => _.includes(item.AllStatuses, 4096) || _.includes(item.AllStatuses, 256);
      // 判断是否异常，但【不是离线】才算是“可前置的异常”
      const isErrorButNotOffline = (item) =>
        (!isOffline(item)) && (_.includes(item.AllStatuses, 128) || _.includes(item.AllStatuses, 64));

      const aIsError = isErrorButNotOffline(a);
      const bIsError = isErrorButNotOffline(b);
      const aIsOffline = isOffline(a);
      const bIsOffline = isOffline(b);

      // 1. 【纯异常】（非离线）排最前面
      if (aIsError && !bIsError) return -1;
      if (!aIsError && bIsError) return 1;

      // 2. 【离线】（含“异常+离线”）排最后
      if (!aIsError && !bIsError) { // 两者都不是“纯异常”
        if (aIsOffline && !bIsOffline) return 1;   // a 离线，a 在后
        if (!aIsOffline && bIsOffline) return -1;  // b 离线，b 在后
      }

      // 3. 其他情况（都非异常且都非离线，或同为离线），按车号排序
      return a.Vid - b.Vid;
    });
    rcs2AgvList.value = data;
    isAgvListLoading.value = false;
  }

  function updateRcsAgv(vehicle: RcsAgvInfoUpdateVo) {
    const agv = _.find(rcs2AgvList.value, agv => agv.Vid === vehicle.Vid);
    if (agv) {
      // Object.assign(agv, vehicle)
      agv.CurrentX = vehicle.X;
      agv.CurrentY = vehicle.Y;
      agv.CurrentZ = vehicle.Z;
      agv.RackNo = vehicle.RackNo;
      agv.Direction = vehicle.Direction;
      // agv.DisplayStatus = vehicle.DisplayStatus;
      agv.State = vehicle.State;
      agv.IsBusinessWorking = vehicle.IsBusinessWorking;
    }
  }

  const agvList = computed(() => {
    // 从 RcsAgvInfoVo 类型转换为 AgvStateVo 类型
    const rcsAgvs = [...rcs2AgvList.value];

    // 合并自定义车列表，如果车号重复，优先使用自定义车的IP，其他属性使用RCS车的属性
    const mergedAgvs: Partial<RcsAgvInfoVo>[] = [...rcsAgvs];

    customAgvList.value.forEach(customAgv => {
      const existingIndex = mergedAgvs.findIndex(agv => agv.Vid === parseInt(customAgv.agvId));

      if (existingIndex >= 0) {
        // 如果存在重复车号，更新IP为自定义车的IP
        mergedAgvs[existingIndex].IpAddr = customAgv.ip;
      } else {
        // 如果不存在重复车号，添加自定义车
        mergedAgvs.push({
          Vid: parseInt(customAgv.agvId),
          IpAddr: customAgv.ip
        } as RcsAgvInfoVo);
      }
    });

    return mergedAgvs;
  });

  const selectedAgvEntity = computed(() => {
    if (!selectedAgvId.value) return null;
    return agvList.value.find(agv => ('' + agv.Vid) === selectedAgvId.value);
  });

  function refreshData() {
    isAgvListLoading.value = true;
    LCC.emit('RefreshAgvList');
  }

  function setSelectedAgv(agv: RcsAgvInfoVo) {
    selectedAgvId.value = '' + (agv?.Vid || 0);
    selectedAgvIp.value = agv?.IpAddr || '';
  }

  // 初始化时加载自定义车列表
  initializeCustomAgvList().finally();

  return {
    isAgvListLoading,
    rcs2AgvList,
    customAgvList,
    agvList,

    selectedAgvId,
    selectedAgvIp,
    selectedAgvEntity,
    refreshData,
    setSelectedAgv,

    updateRcsAgv,
    updateAgvList,
    clearList,
    addCustomAgv,
    removeCustomAgv
  };
});

function getDirection(origin: RcsAgvInfoVo): LCCDirection | '' {
  if (origin.Direction === 0) {
    return 'RIGHT';
  } else if (origin.Direction === 1) {
    return 'DOWN';
  } else if (origin.Direction === 2) {
    return 'LEFT';
  } else if (origin.Direction === 3) {
    return 'UP';
  }
  return '';
}

function getAgvType(origin: RcsAgvInfoVo) {
  if (_.startsWith(origin.AGVModel, 'CYBER-LIFT')) {
    return 'CL';
  }
  if (_.startsWith(origin.AGVModel, 'CC-')) {
    return 'CC';
  }
  if (_.startsWith(origin.AGVModel, 'CS2_')) {
    return 'CS';
  }
}

export interface RcsAgvInfoUpdateVo {
  /*
  {
      "Vid": 52,
      "RackNo": "",
      "X": -1.708,
      "Y": 1.411,
      "Z": 1,
      "Direction": 0,
      "DisplayStatus": 1,
      "Status": 1,
      "State": 1,
      "IsBusinessWorking": false,
      "Width": 1.68,
      "Height": 0.5,
      "Length": 1.68,
      "VehicleModel": "",
      "Type": 0,
      "Ip": ""
  }
   */
  Vid: number;
  RackNo: string;
  X: number;
  Y: number;
  Z: number;
  Direction: number;
  DisplayStatus: RcsDisplayStatus;
  Status: number;
  State: number;
  IsBusinessWorking: boolean;
  Width: number;
  Height: number;
  Length: number;
  VehicleModel: string;
  Type: number;
  Ip: string;
}

export interface RcsAgvInfoVo {
  Vid: number;
  AssignedRackNo: string;
  RackNo: string;
  PickedRackNo: string;
  Location: number;
  Direction: number;
  // DisplayStatus: RcsDisplayStatus; 这个字段没有了
  LockedNodes: number[] | null;
  AllStatuses: RcsDisplayStatus[];
  AGVModel: string;
  IpAddr: string;
  Type: number;
  IsManualLock: boolean;
  Battery: number;
  AssignedDockCode: string;
  AssignedRestCoord: string;
  AssignedStationCode: string;
  ParentTaskNo: string;
  TaskNo: string;
  InnerTaskNo: string;
  Group: number;
  IsBusinessWorking: boolean;
  IsInterrupted: boolean;
  Width: number;
  Height: number;
  Length: number;
  ChargingStartTime: string;
  State: number;
  CurrentX: number;
  CurrentY: number;
  CurrentZ: number;
  IsAuto: number;
  IsLiftUp: boolean;
  IsForceLock: boolean;
  IsTraversalTesting: boolean;
  RGVInfo: any;
  /*
"Vid": 3,
  "AssignedRackNo": "",
  "RackNo": "",
  "PickedRackNo": "",
  "Location": 0,
  "Direction": 0,
  "DisplayStatus": 1,
  "LockedNodes": null,
  "AllStatuses": [1],
  "AGVModel": "CYBER-LIFT-A_V1.0",
  "IpAddr": "10.10.116.43",
  "Type": 1024,
  "IsManualLock": false,
  "Battery": 78,
  "AssignedDockCode": "",
  "AssignedRestCoord": "",
  "AssignedStationCode": "",
  "ParentTaskNo": "",
  "TaskNo": "",
  "InnerTaskNo": "",
  "Group": 1024,
  "IsBusinessWorking": false,
  "IsInterrupted": false,
  "Width": 1.68,
  "Height": 0.5,
  "Length": 1.68,
  "ChargingStartTime": "2025-07-17T16:41:01.261860779+08:00",
  "State": 2,
  "CurrentX": -1,
  "CurrentY": -1,
  "CurrentZ": -1,
  "IsAuto": 0,
  "IsLiftUp": false,
  "IsForceLock": false,
  "IsTraversalTesting": false,
  "RGVInfo": null
   */
}

export interface CustomAgvInfo {
  agvId: string;
  ip: string;
  type: string;
  isOnline: boolean;
  displayStatus: number;
  mode: string;
  soc: number;
  logicX: number;
  logicY: number;
  direction: string;
  agvModelType: string;
  httpPort: number;
  wsPort: number;
}
